﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using HealthCardService.Model;
using System.Linq;

namespace HealthCardService.Common
{
    public static class SignHelper
    {
        public static string getSign(IDictionary<String, Object> commonIn, IDictionary<String, Object> req)
        {
            SortedDictionary<String, Object> sortParamDic = new SortedDictionary<String, Object>(commonIn);
            foreach (KeyValuePair<string, Object> kv in req)
            {
                sortParamDic.Add(kv.Key, kv.Value);
            }

            string paramStr = getParamStr(sortParamDic);

            Console.WriteLine("param str:" + paramStr);

            byte[] bytes = Encoding.UTF8.GetBytes(paramStr + AppSettings.AppSetting("AppSecret"));
            byte[] hash = SHA256.Create().ComputeHash(bytes);

            string sign = Convert.ToBase64String(hash);
            return sign;
        }

        private static string getParamStr(SortedDictionary<String, Object> sortParamDic)
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (KeyValuePair<string, Object> kv in sortParamDic)
            {
                if (kv.Value == null)
                {
                    continue;
                }
                string val;
                if (IsBaseType(kv.Value))
                {
                    val = kv.Value.ToString();
                }
                else
                {
                    val = JsonConvert.SerializeObject(kv.Value);
                    Console.WriteLine(val);
                }

                if (val.Trim().Equals(""))
                {
                    continue;
                }

                if (stringBuilder.Length > 0)
                {
                    stringBuilder.Append("&");
                }
                stringBuilder.Append(kv.Key);
                stringBuilder.Append("=");
                stringBuilder.Append(val);
            }

            return stringBuilder.ToString();
        }

        private static bool IsBaseType(Object obj)
        {
            Type type = obj.GetType();
            return type.IsPrimitive || type.Equals(typeof(string));
        }

    }
}
